<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/columnPage/columnPageClassify' }">栏目页列表</el-breadcrumb-item>
            <el-breadcrumb-item>专题页富文本内容页</el-breadcrumb-item>
        </el-breadcrumb>

        <div style="margin-top: 24px;">
            <el-button size="small" type="primary" @click="backPage()">返回</el-button>
            <el-button size="small" type="primary" @click="submit">保存</el-button>
        </div>
        <div style="margin-top: 20px;"></div>
        <quill-editor v-model="formData.text" :options="editorOption" style="height: 600px;" ref="QuillEditor">
        </quill-editor>
        <el-dialog title="选择图片" :visible.sync="uploadVisible" width="30%">
            <div>
                <div class="upload-demo">
                    <el-upload action="" :http-request="mainImgUpload" :show-file-list="false" list-type="picture-card">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <!-- <img v-if="formData.mainImg" :src="formData.mainImg" class="avatar"> -->

                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>

import {
    addTextTails, selectTextTailByIndexIds, updateTextTails
} from "../../api/userMG";
import Pagination from "../../components/Pagination";
import client from "@/utils/ossClient.js";
import VueQuillEditor from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
// 工具栏配置
const toolbarOptions = [
    ["bold", "italic", "underline", "strike"], // toggled buttons
    ["blockquote", "code-block"],

    [{ header: 1 }, { header: 2 }], // custom button values
    [{ list: "ordered" }, { list: "bullet" }],
    [{ script: "sub" }, { script: "super" }], // superscript/subscript
    [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
    [{ direction: "rtl" }], // text direction

    [{ size: ["small", false, "large", "huge"] }], // custom dropdown
    [{ header: [1, 2, 3, 4, 5, 6, false] }],

    [{ color: [] }, { background: [] }], // dropdown with defaults from theme
    [{ font: [] }],
    [{ align: [] }],
    ["link", "image", "video"], // 对于图片上传这是重点
    ["clean"], // remove formatting button
];
export default {
    data() {
        return {
            formData: {
                text: '',
                id: "",
            },
            uploadVisible: false,
            activeName: 'first',
            loading: false, //是显示加载
            editFormVisible: false, //控制编辑页面显示与隐藏
            menuAccessshow: false, //控制数据权限显示与隐藏
            title: "添加",
            name: "",
            sort_order: "",
            // 删除
            seletedata: {
                ids: "",
                token: localStorage.getItem("logintoken"),
            },
            listData: [], //用户数据
            // 选中
            checkmenu: [],
            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 10,
                total: 10,
            },
            columnPageItem: {},
            editorOption: {
                modules: {
                    toolbar: {
                        container: toolbarOptions, // 工具栏
                        handlers: {
                            image: (value) => {
                                if (value) {
                                    // 在这里编写图片按钮点击操作
                                    this.uploadVisible = true;
                                    this.cursorIndex =
                                        this.$refs.QuillEditor.quill.getSelection().index;
                                } else {
                                    this.quill.format("image", false);
                                }
                            },
                        },
                    },
                },
            },
        };
    },
    // 注册组件
    components: {
        Pagination,
    },
    /**
     * 数据发生改变
     */
    watch: {},
    /**
     * 创建完毕
     */
    created() {
        let obj = JSON.parse(localStorage.getItem('columnPageItem')) || ''
        if (!obj == '') {
            console.log('11')
            this.columnPageItem = obj
        } else {
            console.log('22')

        }
        this.getdata()

    },
    /**
     * 里面的方法只有被调用才会执行
     */

    methods: {
        backPage() {
            this.$router.go(-1);
        },
        submit() {
            this.loading = true;
            var formData = JSON.parse(JSON.stringify(this.formData))
            let columnPageItem = JSON.parse(localStorage.getItem('columnPageItem'))
            this.formData.indexId = columnPageItem.id
            if (this.formData.id) {
                this.formData.id = Number(this.formData.id)
                updateTextTails(this.formData).then(res => {
                    this.loading = false
                    if (res.code == 200) {
                        this.editFormVisible = false
                        this.$message({
                            type: "success",
                            message: res.msg,
                        });
                        
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                addTextTails(this.formData).then((res) => {
                    this.loading = false
                    if (res.code == 200) {
                        this.editFormVisible = false
                        this.$message({
                            type: "success",
                            message: res.msg,
                        });
                       
                    } else {
                        this.$message.error(res.msg);
                    }
                });
            }

        },
        mainImgUpload(file) {
            var self = this;
            //判断扩展名
            const tmpcnt = file.file.name.lastIndexOf(".");
            const exname = file.file.name.substring(tmpcnt + 1);
            const names = ["jpg", "jpeg", "webp", "png", "bmp"];
            // if (names.indexOf(exname) < 0) {
            //   this.$message.error("不支持的格式!");
            //   return;
            // }
            const fileName = file.file.uid + "." + exname;
            client
                .put(fileName, file.file)
                .then((res) => {
                    if (res.url) {

                        self.getUrl(res.url);
                    } else {
                        this.$message.error("文件上传失败");
                    }
                })
                .catch((err) => { });
        },

        getUrl(url) {
            this.uploadVisible = false;
            // 获取富文本组件实例
            let quill = this.$refs.QuillEditor.quill;
            // 如果上传成功
            if (url) {
                // 插入图片，res为服务器返回的图片链接地址

                quill.insertEmbed(this.cursorIndex, "image", url);
                // 调整光标到最后
                quill.setSelection(this.cursorIndex + 1);
            } else {
                // 提示上传失败信息
            }
        },
        // 获取数据方法
        getdata() {
            selectTextTailByIndexIds({
                indexId: this.columnPageItem.id
            }).then((res) => {
                this.loading = false;
                if (res.code == 200) {
                    let lst = res.data.data
                    console.log('thislst====', lst)
                    this.formData = lst[0];
                    console.log('this.formData.text====', this.formData.text)
                    return;
                }
                this.$message({
                    type: "info",
                    message: res.msg,
                });
            });
        },
        // 分页插件事件
        callFather(parm) {
            this.formInline.page = parm.currentPage;
            this.formInline.limit = parm.pageSize;
            this.getdata(parm.currentPage);
        },

        //显示编辑界面
        handleEdit: function (row) {
            console.log("row", row);
            this.editFormVisible = true;
            if (row != undefined && row != "undefined") {
                this.title = "修改";
                this.id = row.id;
                this.name = row.name;
                this.sort_order = row.sort_order;
            } else {
                this.title = "添加";
                this.name = "";
                this.sort_order = "";
            }
        },

        // 删除
        deleteCategory(index, row) {
            this.$confirm("确定要删除吗?", "信息", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    deleteCategory({ id: row.id })
                        .then((res) => {
                            if (res.code == 200) {
                                this.$message({
                                    type: "success",
                                    message: "已删除！",
                                });
                                this.getdata();
                            } else {
                                this.$message({
                                    type: "info",
                                    message: res.msg,
                                });
                            }
                        })
                        .catch((err) => {
                            this.loading = false;
                            this.$message.error("删除失败，请稍后再试！");
                        });
                })
                .catch(() => {
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },

        // 关闭编辑、增加弹出框
        closeDialog(dialog) {
            if (dialog == "edit") {
                this.editFormVisible = false;
            } else if (dialog == "perm") {
                this.menuAccessshow = false;
            }
        },
    },
};
</script>

<style scoped>
.user-search {
    margin-top: 20px;
}

.userRole {
    width: 100%;
}
</style>